package com.doubi.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.SneakyThrows;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AlipayUtil {

    /**
     * MrDoubi
     * 2020年3月18日 13:19:56
     * 支付宝下单
     *
     * @param orderOid 订单唯一标识
     * @param price    价格
     */
    public static String suspendPayment(String orderOid, BigDecimal price) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.url, AlipayConfig.app_id, AlipayConfig.private_key
                , AlipayConfig.format, AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.signtype);
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("完美宴会订单");//商品信息
        model.setSubject("完美宴会订单");//商品名称
        model.setOutTradeNo(orderOid);//订单号
        model.setTimeoutExpress("30m");//支付超时时间
            /*
        model.setTotalAmount(String.valueOf(payParameter.getActualPrice()));// 支付金额
            */
        model.setTotalAmount(String.valueOf(0.01));// 支付金额
        request.setBizModel(model);
        // 回调地址(充值订单)
        request.setNotifyUrl(AlipayConfig.notify_url);// 回调地址
        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * MrDoubi
     * 2020年3月18日 13:26:25
     * 支付宝验证
     *
     * @param request req
     * @return boolean
     */
    public static String signVerified(HttpServletRequest request)  {
        Map<String, String> params = new HashMap<>();
        //从支付宝回调的request域中取值
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        //商品订单号
        String out_trade_no = request.getParameter("out_trade_no");            // 商户订单号
        // 当前交易状态
        String tradeStatus = request.getParameter("trade_status");            //交易状态
        // 支付金额
        String totalAmount = request.getParameter("total_amount");            //交易状态
        // 支付时间
        String payDate = request.getParameter("gmt_payment");            //交易状态
        //3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;
        try {
            //3.1调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.signtype);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println("tradeStatus:  ----------------->   " + tradeStatus);
        System.out.println("signVerified:  ----------------->   " + signVerified);
        System.out.println("totalAmount:  ----------------->   " + totalAmount);
        System.out.println("out_trade_no:  ----------------->   " + out_trade_no);
        //对验签进行处理
        if (signVerified) {
            //验签通过
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                return out_trade_no;
            }
        }
        return null;
    }


    @SneakyThrows
    public static void refundOrder(String orderOid, BigDecimal price) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.url, AlipayConfig.app_id, AlipayConfig.private_key, AlipayConfig.format, AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.signtype);//支付宝需要的参数serverUrl、appId、private_key、format、charset、public_key、signType
        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
        refundModel.setTradeNo(orderOid);
        //refundModel.setRefundAmount(String.valueOf(price));
        refundModel.setRefundAmount(String.valueOf(0.01));
        refundModel.setRefundReason("订单退款");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizModel(refundModel);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        System.out.println(response.getMsg() + "\n");
        System.out.println(response.getBody());
    }
}
